
<html>  
  <head>  
        <meta charset="utf-8">  
        <title>我去过的城市</title>  
  </head> 

<style>


</style>
    <body style="margin:0 auto;text-align:center;">
      <h3>我去过的城市</h3>  
		<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>  
        <script>		   
					   
		var nodes = [ {name:"黄冈"}, 
                  { name: "武汉"},
                  {name:"大连",index:2},
                  {name:"香港",index:3},
                  { name: "桂林",index:4    },
					        { name: "厦门",index:5 },
                  { name:"惠州",index:6}, 
                  { name: "北京",index:7   },
                   {name: "广州" ,index:8},
                   {name:"东莞",index:9 },
                   {name:"深圳",index:10},
                   {name:"沈阳",inex:11},
                   ];
					 
		var edges = [  { source : 0  , target: 1 } ,{ source : 0  , target: 9 } ,{ source : 9  , target: 5 },
                  {source:1, target:7},{source:7, target:11},{source:11,target:2},
                  {source:0,target:8}, { source : 8  , target: 9} , { source : 8  , target: 10 } , { source : 10  , target: 0 } , { source : 10  , target: 4 } , { source : 10  , target: 3 },{source:10, target:6} ];	
		
		var width = 980;
		var height = 740;
		
		
		var svg = d3.select("body")
					.append("svg")
					.attr("width",width)
					.attr("height",height);
		
		var force = d3.layout.force()
				.nodes(nodes)		//指定节点数组
				.links(edges)		//指定连线数组
				.size([width,height])	//指定范围
				.linkDistance(180)	//指定连线长度
				.charge(-500);	//相互之间的作用力

		force.start();	//开始作用

		console.log(nodes);
		console.log(edges);
		
		//添加连线		
		var svg_edges = svg.selectAll("line")
							.data(edges)
							.enter()
							.append("line")
							.style("stroke","#ccc")
							.style("stroke-width",1);
		
		var color = d3.scale.category20();
				
		//添加节点			
		var svg_nodes = svg.selectAll("circle")
							.data(nodes)
							.enter()
							.append("circle")
							.attr("r",20)
							.style("fill",function(d,i){
								return color(i);
							})
							.call(force.drag);	//使得节点能够拖动

		//添加描述节点的文字
		var svg_texts = svg.selectAll("text")
							.data(nodes)
							.enter()
							.append("text")
							.style("fill", "black")
							.attr("dx", 20)
							.attr("dy", 8)
							.text(function(d){
								return d.name;
							});
					

		force.on("tick", function(){	//对于每一个时间间隔
		
			 //更新连线坐标
			 svg_edges.attr("x1",function(d){ return d.source.x; })
			 		.attr("y1",function(d){ return d.source.y; })
			 		.attr("x2",function(d){ return d.target.x; })
			 		.attr("y2",function(d){ return d.target.y; });
			 
			 //更新节点坐标
			 svg_nodes.attr("cx",function(d){ return d.x; })
			 		.attr("cy",function(d){ return d.y; });

			 //更新文字坐标
			 svg_texts.attr("x", function(d){ return d.x; })
			 	.attr("y", function(d){ return d.y; });
		});
		  
        </script>  
		
    </body>  
</html>  
